<template>
  <el-row>
    <el-col :span="4">
      <el-card style="margin-right: 15px;">
        <template #header>
          <el-input placeholder="部门名称" clearable>
            <template #append>
              <el-link>搜索</el-link>
            </template>
          </el-input>
        </template>
        <el-tree :data="depts" @node-click="handleNodeClick" :highlight-current="true" default-expand-all
          :props="{ children: 'children', label: 'name', disabled: '' }" />
      </el-card>
    </el-col>

    <el-col :span="20">
      <div class="search">
        <el-form :inline="true">
          <el-form-item label="关键字" prop="name">
            <el-input placeholder="用户名称" v-model="userInput.KeyWord" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchUser">搜索</el-button>
            <el-button @click.stop="resetUser">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card>
        <template #header>
          <el-button type="success" @click.stop="add">新增</el-button>
          <el-button type="danger" v-show="false">删除</el-button>
        </template>

        <div class="box-list">
          <el-table :data="users.list" border style="width: 100%">
            <el-table-column prop="userName" label="用户名" width="auto" />
            <el-table-column prop="nickName" label="用户昵称" width="auto" />
            <el-table-column prop="avatar" label="头像" width="auto">
              <template #default="scope">
                <img :src="getFileUrl(scope.row.avatar)" class="avatar">
              </template>
            </el-table-column>
            <el-table-column prop="gender" label="性别" width="120">
              <template #default="scope">
                <el-text v-if="scope.row.gender == 0">未知</el-text>
                <el-text v-if="scope.row.gender == 1">男</el-text>
                <el-text v-if="scope.row.gender == 2">女</el-text>
              </template>
            </el-table-column>
            <el-table-column prop="deptName" label="部门" width="180" />
            <el-table-column prop="mobile" label="手机号码" width="180" />
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-text v-if="scope.row.status == 0">正常</el-text>
                <el-text v-if="scope.row.status == 1">禁用</el-text>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
            <el-table-column label="操作" width="240" align="center">
              <template #default="scope">
                <el-button text type="primary" size="small" @click.stop="edit(scope.row)">编辑</el-button>
                <el-button text type="warning" size="small" @click.stop="remove(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination class="page" v-model:current-page="userInput.pageNo" v-model:page-size="userInput.pageSize"
            @update:page-size="searchUser" @update:current-page="searchUser" :background="true"
            layout="sizes, prev, pager, next" :page-sizes="[10, 20, 30, 50]" :total="users.count" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <el-dialog v-model="dialogModel.dialogVisible" :title="dialogModel.title" :width="700">
    <el-form class="dialog" label-width="100px" :rules="rules" ref="ruleFormRef" :model="user">
      <el-form-item label="头像:" prop="avatar">
        <image-select v-model:image-url="avatarUrl" v-model:file="avatarFile" class="avatar" />
      </el-form-item>
      <el-form-item label="用户名:" prop="userName">
        <el-input placeholder="请输入用户名" clearable v-model="user.userName" />
      </el-form-item>
      <el-form-item label="用户昵称:" prop="nickName">
        <el-input placeholder="请输入用户昵称" clearable v-model="user.nickName" />
      </el-form-item>
      <el-form-item label="所属部门:" prop="deptId">
        <el-tree-select placeholder="请选择所属部门" :data="depts"
          :props="{ label: 'name', children: 'children', value: 'id' }" v-model="user.deptId" check-strictly
          :render-after-expand="false" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select placeholder="请选择" v-model="user.gender">
          <el-option label="未知" :value="0" />
          <el-option label="男" :value="1" />
          <el-option label="女" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="roleIds">
        <el-select multiple placeholder="请选择" v-model="user.roles">
          <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id ?? 0" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号:" prop="mobile">
        <el-input placeholder="请输入手机号" clearable v-model="user.mobile" />
      </el-form-item>
      <el-form-item label="邮箱:" prop="email">
        <el-input placeholder="请输入邮箱" clearable v-model="user.email" />
      </el-form-item>
      <el-form-item label="密码:" prop="passWord">
        <el-input placeholder="请输入密码" clearable v-model="user.passWord" />
      </el-form-item>
      <el-form-item label="状态:" prop="status">
        <el-radio-group v-model="user.status">
          <el-radio :label="0">正常</el-radio>
          <el-radio :label="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click.stop="commit">确 定</el-button>
        <el-button @click.stop="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getSysDept } from "@/api/dept/index"
import { IDept, IDeptInput, IDeptTree } from "@/api/dept/type"
import { getSysRole } from "@/api/role/index"
import { IRole } from "@/api/role/type"
import { IUser, IUserInput, getRules } from "@/api/user/type"
import { addUser, getUserPage, deleteUser, UpdateUser, getUser } from "@/api/user/index"
import { uploadFile, getFileUrl } from "@/api/fileManage/index"
import { reactive, ref } from "vue"
import { Dialog } from "@/utils/dialog"
import { IPageOutput, ConfirmDialog, validateForm } from "@/utils/common"
import { ElMessage } from "element-plus";
import ImageSelect from "@/components/ImageSelect.vue"
import type { FormInstance } from 'element-plus'

// view-model定义
const dialogModel = reactive(new Dialog())
const deptInput = reactive<IDeptInput>({});
const depts = ref<IDeptTree[]>([]);
const roles = ref<IRole[]>([]);
const user = ref<IUser>({});
const users = ref<IPageOutput<IUser>>({
  count: 0,
  list: [],
});
const userInput = ref<IUserInput>({
  pageNo: 1,
  pageSize: 10,
});
const avatarUrl = ref("");
const avatarFile = ref<File | undefined>();
const rules = getRules();
// 表单实例
const ruleFormRef = ref<FormInstance | null>(null);

// 角色数据获取
const getRoles = async () => {
  roles.value = (await getSysRole()).data;
}
getRoles();

// 部门数据获取
const deptSearch = async () => {
  let data = await getSysDept(deptInput);
  depts.value = data.data;
}
deptSearch();

// 用户操作
const add = () => {
  dialogModel.show("新增")

  avatarUrl.value = "";
  user.value = {
    email: "",
    status: 0,
  };
}
const edit = async (updateUser: IUser) => {
  dialogModel.show("编辑");

  user.value = (await getUser(updateUser.id ?? 0)).data;
  avatarUrl.value = getFileUrl(user.value.avatar ?? "");
}
const remove = (id: number) => {
  ConfirmDialog("确认删除?",
    async () => {
      await deleteUser(id);
      await searchUser();
      ElMessage({
        type: 'success',
        message: '删除成功',
      });
    },
    () => {
      ElMessage({
        type: 'info',
        message: '删除取消',
      });
    });
}

const searchUser = async () => {
  users.value = (await getUserPage(userInput.value)).data
}
searchUser();

const resetUser = async () => {
  userInput.value.KeyWord = "";
  userInput.value.deptId = undefined;
  await searchUser();
}

const handleNodeClick = (data: IDept, node: any) => {
  userInput.value.deptId = data.id;
  searchUser();
}

const closeDialog = () => {
  dialogModel.close();
}

const commit = async () => {
  validateForm(ruleFormRef).then(async () => {
    if (dialogModel.title == "新增") {
      if (avatarFile && avatarFile.value != undefined) {
        user.value.avatar = (await uploadFile(avatarFile.value)).data;
        avatarFile.value = undefined;
      }
      await addUser(user.value);
    }
    else if (dialogModel.title = "编辑") {
      if (avatarFile.value != undefined) {
        user.value.avatar = (await uploadFile(avatarFile.value)).data;
        avatarFile.value = undefined;
      }
      await UpdateUser(user.value)
    }
    await searchUser();
    closeDialog();
  })
}
</script>

<style scoped>
.is-focusable {
  background-color: #53a7cd;
}

.avatar {
  height: 30px;
  width: 30px;
  border-radius: 50%;
}
</style>